package com.example.lightenergypolymerize.controller;

import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lightenergypolymerize.entity.Answer;
import com.example.lightenergypolymerize.entity.enums.AiModelEnum;
import com.example.lightenergypolymerize.entity.enums.AiTypeEnum;
import com.example.lightenergypolymerize.service.IAnswerService;
import com.example.lightenergypolymerize.util.AppVariable;
import com.example.lightenergypolymerize.util.ResponseEntity;
import com.example.lightenergypolymerize.util.SecurityUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/xunfei")
public class XunFeiController {
    @Value("${xunfei.chat.url}")
    private String chatUrl;
    @Value("${xunfei.chat.api-key}")
    private String chatApiKey;
    @Value("${xunfei.chat.api-secret}")
    private String chatApiSecret;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;

    @RequestMapping("/chat")
    public ResponseEntity chat(String question) throws JsonProcessingException {
        if(!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }

        String content = "";//大模型返回的结果
        boolean addResult = false;//数据是否添加到了数据库
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        //1.获取分布式锁示例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            //2.获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                //获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口");
            }
            String bodyJson = "{\n" +
                    "    \"model\":\"generalv3.5\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "    ],\n" +
                    "    \"stream\": false\n" +
                    "}";
            String result = HttpRequest.post(chatUrl)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + chatApiKey + ":" + chatApiSecret)
                    .body(bodyJson)
                    .execute()
                    .body();
            HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            if (!resultMap.get("code").toString().equals("0")) {
                return ResponseEntity.fail(resultMap.get("message").toString());
            }
            ArrayList choices = (ArrayList) resultMap.get("choices");
            LinkedHashMap<String, Object> choicesMap = (LinkedHashMap<String, Object>) choices.get(0);
            LinkedHashMap<String, Object> message = (LinkedHashMap<String, Object>) choicesMap.get("message");
            content = message.get("content").toString();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(content);
            answer.setModel(AiModelEnum.XUNFEI.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            addResult = answerService.save(answer);
        }catch (Exception e) {
        }finally {
            //3.释放分布式锁
            rLock.unlock();
        }
        if(addResult) {
            return ResponseEntity.succ(content);
        }
        return ResponseEntity.fail("操作失败，请重试！");
    }

    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
        queryWrapper.eq("model", AiModelEnum.XUNFEI.getValue());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.succ(answerService.list(queryWrapper));
    }
}
